package com.robot.admin.controller;


import com.alibaba.fastjson.JSON;

import com.robot.admin.client.MerchantClient;
import com.robot.admin.pojo.client.Industry;
import entity.Result;
import entity.StatusCode;
import io.jsonwebtoken.Claims;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import util.CheckUtil;
import util.UpdateUtil;

import javax.servlet.http.HttpServletRequest;
import java.time.LocalDateTime;
import java.util.List;

/**
 * @author lin
 */
@RestController
@CrossOrigin
@RequestMapping("/industry")
public class IndustryController {
    @Autowired
    private MerchantClient merchantClient;
    @Autowired
    private CheckUtil checkUtil;
    @Autowired
    private HttpServletRequest request;

    private final Logger logger = LoggerFactory.getLogger(this.getClass());


    /**
     * 商家行业列表
     *
     * @return
     */
    @RequestMapping(value = "findIndustries", method = RequestMethod.POST, produces = "application/json;charset=utf-8")
    public Result findIndustries() {
        Claims claims = (Claims) request.getAttribute("robot_admin");
        if (claims == null) {
            return new Result(StatusCode.ERROR_TOKEN_EXPIRED);
        }
        logger.info("claims.id="+claims.getId());
        List<Industry> industriesInDb = JSON.parseArray(merchantClient.thirdFindIndustries(), Industry.class);
        logger.info("industriesInDb=" + industriesInDb);
        return new Result(StatusCode.SUCCESS_QUERY, industriesInDb);
    }

    /**
     * 根据id查找行业
     *
     * @param id
     * @return
     */
    @RequestMapping(value = "findIndustryById/{id}", method = RequestMethod.GET, produces = "application/json;charset=utf-8")
    public Result findIndustryById(@PathVariable String id) {
        Claims claims = (Claims) request.getAttribute("robot_admin");
        if (claims == null) {
            return new Result(StatusCode.ERROR_TOKEN_EXPIRED);
        }
        logger.info("claims.id="+claims.getId());
        Industry industryInDb = JSON.parseObject(merchantClient.thirdFindIndustryById(id), Industry.class);
        logger.info("industryInDb=" + industryInDb);
        if (industryInDb == null) {
            return new Result(StatusCode.ERROR, "行业不存在");
        }
        return new Result(StatusCode.SUCCESS_QUERY, industryInDb);
    }

    /**
     * 增加
     *
     * @param industry
     */
    @RequestMapping(value = "addIndustry", method = RequestMethod.POST, produces = "application/json;charset=utf-8")
    public Result addIndustry(@RequestBody Industry industry) {
        logger.info("industry=" + industry);
        Claims claims = (Claims) request.getAttribute("robot_admin");
        if (claims == null) {
            return new Result(StatusCode.ERROR_TOKEN_EXPIRED);
        }
        logger.info("claims.id="+claims.getId());
        if (industry.getName() == null || "".equals(industry.getName())) {
            return new Result(StatusCode.ERROR, "行业必填");
        }
        if (industry.getImageUrl() == null || "".equals(industry.getImageUrl())) {
            return new Result(StatusCode.ERROR, "请上传行业小图标");
        }
        if (!checkUtil.checkImage(industry.getImageUrl())) {
            return new Result(StatusCode.ERROR, "请上传正确格式的行业小图标");
        }
        logger.info("industry' sort=" + industry.getSort());
        Industry industryInDb = JSON.parseObject(merchantClient.thirdFindIndustryByName(JSON.toJSONString(industry)), Industry.class);
        logger.info("industryInDb=" + industryInDb);
        if (industryInDb != null) {
            logger.info("industryInDb'deletedAt=" + industryInDb.getDeletedAt());
            return new Result(StatusCode.ERROR, "行业名称已存在" + industryInDb);
        }
        merchantClient.thirdAddIndustry(JSON.toJSONString(industry));
        return new Result(StatusCode.SUCCESS_INSERTED);

    }

    /**
     * 修改
     *
     * @param industry
     */
    @RequestMapping(value = "updateIndustry/{id}", method = RequestMethod.PUT, produces = "application/json;charset=utf-8")
    public Result updateIndustry(@RequestBody Industry industry, @PathVariable String id) {
        Claims claims = (Claims) request.getAttribute("robot_admin");
        if (claims == null) {
            return new Result(StatusCode.ERROR_TOKEN_EXPIRED);
        }
        logger.info("claims.id="+claims.getId());
        Industry industryInDb = JSON.parseObject(merchantClient.thirdFindIndustryById(id), Industry.class);
        logger.info("industryInDb=" + industryInDb);
        if (industryInDb == null) {
            return new Result(StatusCode.ERROR, "行业不存在");
        }
        if (industryInDb.getDeletedAt() != null) {
            return new Result(StatusCode.ERROR, "行业已删除");
        }
        if (industry.getName() != null) {
            Industry industryInDbByName = JSON.parseObject(merchantClient.thirdFindIndustryByName(JSON.toJSONString(industry)), Industry.class);
            logger.info("industryInDbByName=" + industryInDbByName);
            //行业名称存在且id不相等,说明不是同一条记录,即行业名称已存在
            if (industryInDbByName != null && !industryInDbByName.getId().equals(industryInDb.getId())) {
                logger.info("industryInDb'deletedAt=" + industryInDbByName.getDeletedAt());
                return new Result(StatusCode.ERROR, "行业名称已存在" + industryInDbByName);
            }
        }
        industry.setId(industryInDb.getId());
        UpdateUtil.copyNonNullProperties(industry, industryInDb);
        merchantClient.thirdUpdateIndustry(JSON.toJSONString(industry));
        return new Result(StatusCode.SUCCESS_UPDATED);
    }

    /**
     * 软删除
     *
     * @param id
     */
    @RequestMapping(value = "deleteIndustry/{id}", method = RequestMethod.PUT, produces = "application/json;charset=utf-8")
    public Result deleteIndustryByDeletedAt(@PathVariable String id) {
        Claims claims = (Claims) request.getAttribute("robot_admin");
        if (claims == null) {
            return new Result(StatusCode.ERROR_TOKEN_EXPIRED);
        }
        logger.info("claims.id="+claims.getId());
        Industry industryInDb = JSON.parseObject(merchantClient.thirdFindIndustryById(id), Industry.class);
        logger.info("industryInDb=" + industryInDb);
        if (industryInDb == null) {
            return new Result(StatusCode.ERROR, "行业不存在");
        }
        LocalDateTime now = LocalDateTime.now();
        industryInDb.setDeletedAt(now);
        merchantClient.thirdUpdateIndustry(JSON.toJSONString(industryInDb));
        return new Result(StatusCode.SUCCESS_DELETED);
    }

    /**
     * 强删除
     *
     * @param id
     */
    @RequestMapping(value = "deleteIndustry/{id}", method = RequestMethod.DELETE, produces = "application/json;charset=utf-8")
    public Result deleteIndustry(@PathVariable String id) {
        Claims claims = (Claims) request.getAttribute("robot_admin");
        if (claims == null) {
            return new Result(StatusCode.ERROR_TOKEN_EXPIRED);
        }
        logger.info("claims.id="+claims.getId());
        merchantClient.thirdDeleteIndustryById(id);
        return new Result(StatusCode.SUCCESS_DELETED);
    }
}
